export const api = {
  getLevels() {
    let levelsDataUrl = 'http://xiang.li/data/codingKids/levels.json'
    if (CC_WECHATGAME) {   // 小游戏需https以及域名服务器配置
      levelsDataUrl = 'https://dev.nownow.club/data/levels.json'
    }
    return fetchJSONRequest(levelsDataUrl)
  }
}

// Promise for XMLHttpRequest
const fetchJSONRequest = (url: string) => {
  return new Promise((resolve, reject) => {
    let xhr = new XMLHttpRequest()
    xhr.onreadystatechange = () => {
      if (xhr.readyState === 4) {
        if (xhr.status >= 200 && xhr.status < 400) {
          resolve(JSON.parse(xhr.responseText))
        } else {
          var resJson = { code: xhr.status, response: xhr.response }
          reject(resJson)
        }
      }
    }
    xhr.open('GET', url, true)
    xhr.send()
  })
}
